package com.yc.service.impl;

import com.yc.service.ScoreQueryService;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ScoreQueryServiceImpl implements ScoreQueryService {

    @Autowired
    @Qualifier("excelEmbeddingStore")
    private EmbeddingStore<TextSegment> embeddingStore;

    @Autowired
    private EmbeddingModel embeddingModel;

    @Override
    public Map<String, Object> queryByStudentId(String sno) {
        try {
            String queryText = "学号:" + sno;
            Embedding queryEmbedding = embeddingModel.embed(queryText).content();

            // 使用 search 方法替代 findRelevant
            EmbeddingSearchResult<TextSegment> searchResult = embeddingStore.search(
                    EmbeddingSearchRequest.builder()
                            .queryEmbedding(queryEmbedding)
                            .maxResults(1)
                            .build()
            );

            if (searchResult.matches().isEmpty()) {
                throw new RuntimeException("未找到学号为 " + sno + " 的学生成绩");
            }

            return buildResult((Map<String, Object>) searchResult.matches().get(0).embedded().metadata());
        } catch (Exception e) {
            return Map.of("error", e.getMessage());
        }
    }

    @Override
    public Map<String, Object> queryByClassAndName(String classes, String sname) {
        try {
            String queryText = "姓名:" + sname + " 班级:" + classes;
            Embedding queryEmbedding = embeddingModel.embed(queryText).content();

            // 使用 search 方法替代 findRelevant
            EmbeddingSearchResult<TextSegment> searchResult = embeddingStore.search(
                    EmbeddingSearchRequest.builder()
                            .queryEmbedding(queryEmbedding)
                            .maxResults(1)
                            .build()
            );

            if (searchResult.matches().isEmpty()) {
                throw new RuntimeException("未找到班级 " + classes + " 中姓名为 " + sname + " 的学生成绩");
            }

            return buildResult((Map<String, Object>) searchResult.matches().get(0).embedded().metadata());
        } catch (Exception e) {
            return Map.of("error", e.getMessage());
        }
    }

    private Map<String, Object> buildResult(Map<String, Object> metadata) {
        Map<String, Object> result = new HashMap<>();
        result.put("studentId", metadata.get("studentId"));
        result.put("name", metadata.get("name"));
        result.put("className", metadata.get("className"));
        result.put("absenceCount", metadata.get("absenceCount"));
        result.put("homeworkAvgScore", metadata.get("homeworkAvgScore"));
        result.put("classPerformance", metadata.get("classPerformance"));
        result.put("finalExamScore", metadata.get("finalExamScore"));
        result.put("totalScore", metadata.get("totalScore"));
        result.put("grade", metadata.get("grade"));
        result.put("remark", metadata.get("remark"));

        // 添加成绩解释
        result.put("explanation", generateExplanation(metadata));
        return result;
    }

    private String generateExplanation(Map<String, Object> metadata) {
        double totalScore = (double) metadata.get("totalScore");
        String grade = (String) metadata.get("grade");
        int absenceCount = (int) metadata.get("absenceCount");

        StringBuilder sb = new StringBuilder();
        sb.append("该生最终成绩为").append(totalScore).append("分，等级评定为").append(grade).append("。");

        if (absenceCount > 0) {
            sb.append("因缺勤").append(absenceCount).append("次，总评扣除了").append(absenceCount * 5).append("分。");
        }

        sb.append("成绩构成：平时作业占40%，课堂表现占20%，期末考试占40%。");

        if (totalScore >= 90) {
            sb.append("表现优秀，各项成绩均衡发展。");
        } else if (totalScore >= 80) {
            sb.append("表现良好，部分科目有提升空间。");
        } else if (totalScore >= 70) {
            sb.append("表现中等，建议加强薄弱环节的学习。");
        } else if (totalScore >= 60) {
            sb.append("表现及格，需要全面加强学习。");
        } else {
            sb.append("表现不及格，建议重修或补考。");
        }

        return sb.toString();
    }
}